package com.hoperun.checkcloth.viewmodel

import androidx.databinding.ObservableField
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.AppUtils
import com.hadilq.liveevent.LiveEvent
import com.hoperun.checkcloth.activity.*
import com.hoperun.checkcloth.repository.Repository
import com.hoperun.checkcloth.ui.LeftOverBoltLoginActivity
import com.hoperun.checkcloth.ui.StuffCheckLoginActivity
import com.hoperun.checkcloth.util.LanguageUtil
import com.hoperun.checkcloth.util.Logger
import kotlinx.coroutines.launch

class HomeViewModel : ViewModel() {
    private val logger = Logger.create("HomeViewModel")
    val version = ObservableField<String>()

    private val _navigation = LiveEvent<String>()
    val navigation: LiveData<String> = _navigation

    private val _upgradeInfo = LiveEvent<Triple<Boolean, String, String>>()
    val upgradeInfo: LiveData<Triple<Boolean, String, String>> = _upgradeInfo

    private val _startCrashExplore = LiveEvent<Boolean>()
    val startCrashExplore: LiveData<Boolean> = _startCrashExplore

    fun init() = viewModelScope.launch {
        version.set(AppUtils.getAppVersionName())
        checkUpgrade()
    }

    fun onGrayClothModuleClicked() {
        _navigation.value = PibuLoginActivity::class.java.name
    }
    fun onjianyanModuleClicked() {
        _navigation.value = PibuLoginActivity::class.java.name
    }
    fun onchangziqueryModuleClicked() {
        _navigation.value = ChangziQueryActivity::class.java.name
    }

    fun onbangbuModuleClicked() {
        _navigation.value = BangbuLoginActivity::class.java.name
    }

    fun onLeftOverBoltModuleClicked() {
        _navigation.value = LeftOverBoltLoginActivity::class.java.name
    }

    fun onStuffCheckModuleClicked() {
        _navigation.value = StuffCheckLoginActivity::class.java.name
    }

    fun onPfgclModuleClicked() {
        _navigation.value = PfgclLoginActivity::class.java.name
    }

    fun onVersionViewClicked() {
        _startCrashExplore.value = true
    }

    fun onLanguageButtonClicked() {
        LanguageUtil.changeLanguage()
    }

    private fun checkUpgrade() {
        viewModelScope.launch {
            Repository.requestNewUpgrade()?.let { (forceUpgrade, versionCode, url) ->
                if (version.get() != versionCode) {
                    Repository.getApkDownloadInfo(url)?.let { path ->
                        _upgradeInfo.value = Triple(forceUpgrade, url, path)
                    }
                }

            }
        }
    }
}